import { getResult, getToken, readData, writeData } from './_utils'

export default [
  // ------------------------------ 登录/登出相关接口 ------------------------------
  /** 👇 登录接口 👇 */
  {
    url: '/mock/login',
    method: 'post',
    response: ({ body }) => {
      const data = readData()
      const { loginName, password } = body as USER.ILoginP
      const curUser = data.users.find((c) => c.loginName === loginName)
      if (curUser) {
        if (curUser.password === password) {
          data.loginUsers[loginName] = `${loginName}_${new Date().getTime()}`
          return getResult(200, '登录成功 !', { token: data.loginUsers[loginName] })
        } else return getResult(500, '密码错误, 请检查密码后重新登录 !')
      } else return getResult(500, '用户不存在 !')
    },
  },

  /** 👇 退出登录接口 👇 */
  {
    url: '/mock/logout',
    method: 'post',
    response: ({ headers }) => {
      const loginName = headers.authorization?.split('_')[0]
      if (loginName) {
        const data = readData()
        data.loginUsers[loginName] = void 0
        writeData(data)
        return getResult(200, '退出登录成功 !')
      } else return getResult(500, '您还未登录 !')
    },
  },

  // ------------------------------ 用户其他相关接口 ------------------------------
  /** 👇 获取用户信息 👇 */
  {
    url: '/mock/userinfo',
    method: 'post',
    response: ({ headers }) => {
      const data = readData()
      const loginName = getToken(headers.authorization)
      const curUser = data.users.find((c) => c.loginName === loginName)
      if (curUser) return getResult(200, '获取角色信息成功 !', curUser)
      else return getResult(500, '获取角色信息失败 !', {})
    },
  },

  /** 👇 获取用户菜单 👇 */
  {
    url: '/mock/menus',
    method: 'post',
    response: ({ headers }) => {
      const data = readData()
      const loginName = getToken(headers.authorization)
      const curUser = data.users.find((c) => c.loginName === loginName)
      if (curUser) {
        const roleIds = curUser?.userRoles || []
        const roles = data.roles.filter((c) => roleIds.includes(c.roleId))
        const menuIds = [...new Set((roles.map((c) => c.roleMenus) || []).flat())]
        const menus = data.menus.filter((c) => menuIds.includes(c.id)) || []
        return getResult(200, '获取菜单成功 !', menus)
      } else return getResult(500, '获取菜单失败 !', [])
    },
  },
] as MOCK.MockMethod[]
